package com.xindaoapp.happypet.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.ByteArrayBuffer;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.AddPet;
import com.xindaoapp.happypet.bean.AddPet.AddPetInfo;
import com.xindaoapp.happypet.bean.PetInfo;
import com.xindaoapp.happypet.bean.PetInfo.Pet;
import com.xindaoapp.happypet.bean.UploadInfo;
import com.xindaoapp.happypet.utils.CalendarManager;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.ProgressHUD;

public class AddPetActivity extends UMBaseActivity implements OnClickListener {
    @ViewInject(R.id.tittle_addpet_cancel)
    private ImageButton tittle_addpet_cancel;
    @ViewInject(R.id.tittle_addpet_content)
    private TextView tittle_addpet_content;
    @ViewInject(R.id.tittle_addpet_ok)
    private TextView tittle_addpet_ok;

    @ViewInject(R.id.pet_name)
    private EditText pet_name;

    // @ViewInject(R.id.spinner_sex)
    // private Spinner spinner_sex;
    // @ViewInject(R.id.spinner_zhonglei)
    // private Spinner spinner_zhonglei;
    // @ViewInject(R.id.spinner_pinzhong)
    // private Spinner spinner_pinzhong;

    @ViewInject(R.id.rl_pet_sex)
    private RelativeLayout rl_pet_sex;
    @ViewInject(R.id.rl_pet_zhonglei)
    private RelativeLayout rl_pet_zhonglei;
    @ViewInject(R.id.rl_pet_pinzhong)
    private RelativeLayout rl_pet_pinzhong;

    @ViewInject(R.id.img_tittle)
    private TextView img_tittle;

    private final String[] sex = new String[] {"公", "母"};
    private final String[] zhonglei = new String[] {"汪星人", "喵星人", "小宠星人", "水星人"};


    // 添加头像
    @ViewInject(R.id.addpet)
    private LinearLayout addpet;
    @ViewInject(R.id.picinfo)
    private RelativeLayout picinfo;
    @ViewInject(R.id.petinfo_touxiang)
    private RelativeLayout petinfo_touxiang;
    @ViewInject(R.id.title_left)
    private ImageButton title_left;
    @ViewInject(R.id.title_right)
    private ImageButton title_right;
    @ViewInject(R.id.pet_img)
    private ImageView pet_img;

    // 初始化选择头像参数
    private static final int CAMERA = 0;
    private static final int ALBUM = 1;
    private static final int PHOTORESOULT = 2;
    private static final String IMAGE_UNSPECIFIED = "image/*";
    private static final int crop = 64;
    protected static final int SUCCESS = 10;
    protected static final int FAIL = 20;
    protected static final int ADDTRUE = 30;
    protected static final int ADDFAIL = 40;

    @ViewInject(R.id.pic_edit)
    private ImageView pic_edit;


    @ViewInject(R.id.pet_birthrday)
    private TextView pet_birthrday;
    @ViewInject(R.id.pet_sex)
    private TextView pet_sex;
    @ViewInject(R.id.pet_zhonglei)
    private TextView pet_zhonglei;
    @ViewInject(R.id.pet_pinzhong)
    private TextView pet_pinzhong;

    @ViewInject(R.id.rl_pet_birthrday)
    private RelativeLayout rl_pet_birthrday;
    private String mFrom = "";



    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    addpet.setVisibility(View.VISIBLE);
                    picinfo.setVisibility(View.GONE);
                    break;
                case 1:
                    Toast.makeText(AddPetActivity.this, "添加失败", 0).show();
                    break;
                case SUCCESS:
                    refurshPets();
                    if (mFrom.equals("change")) {
                        Toast.makeText(getBaseContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getBaseContext(), "添加成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case FAIL:
                    if (mFrom.equals("change")) {
                        Toast.makeText(getBaseContext(), "修改失败", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getBaseContext(), "添加失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case ADDTRUE:
                    refurshPets();
                    Toast.makeText(getBaseContext(), "添加成功", Toast.LENGTH_SHORT).show();
                    // finish();
                    break;
                case ADDFAIL:
                    Toast.makeText(getBaseContext(), "添加失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        };
    };

    private void refurshPets() {
        // 初始化宠物列表
        HappyPetApplication.get().getMoccaApi()
                .getMyPetList(UserState.getUserUid(), new IRequest<PetInfo>() {

                    @Override
                    public void request(PetInfo t) {
                        UserState.setPetInfo(t);
                        Intent data = new Intent();
                        setResult(RESULT_OK, data);
                        finish();
                    }
                });
    }

    private String petid;
    private String petname;
    private String petpic;

    private String petsex = "";
    private String petzhonglei = "";
    private String petzhongleinum = "";
    private String petpinzhong = "";
    private String breedid = "";

    private Pet pet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addpet);
        ViewUtils.inject(this);

        Intent intent = getIntent();
        if (intent.hasExtra("isfrom")) {
            mFrom = intent.getExtras().getString("isfrom");
        }
        petid = intent.getExtras().getString("petid");
        petname = intent.getExtras().getString("petname");
        petpic = intent.getExtras().getString("petpic");

        if (intent.getSerializableExtra("pet") != null) {
            pet = (Pet) intent.getSerializableExtra("pet");
            pet_birthrday.setText(pet.birth);

            petsex = pet.getSex() + "";
            petzhonglei = pet.getPettype();
            petpinzhong = pet.getBreed();
            breedid = pet.getBreedid();


            if (pet.getSex().equals("1")) {
                pet_sex.setText("公");
            }
            if (pet.getSex().equals("2")) {
                pet_sex.setText("母");

            }
            if (pet.getPettype().equals("1")) {
                pet_zhonglei.setText("汪星人");
                petzhongleinum = "1";
            }
            if (pet.getPettype().equals("2")) {
                pet_zhonglei.setText("喵星人");
                petzhongleinum = "2";
            }
            if (pet.getPettype().equals("3")) {
                pet_zhonglei.setText("小宠星人");
                petzhongleinum = "3";
            }
            if (pet.getPettype().equals("4")) {
                pet_zhonglei.setText("水星人");
                petzhongleinum = "4";
            }
            pet_pinzhong.setText(pet.getBreed());

        }
        if (!petpic.equals("")) {
            ImageLoader.getInstance().displayImage(petpic + "?" + Math.random(), pet_img);
        }
        addpet.setVisibility(View.VISIBLE);
        picinfo.setVisibility(View.GONE);
        initClick();
        // initSpinner();
    }



    /*
     * private void initSpinner() { ArrayAdapter<CharSequence> nameAdapter = new
     * ArrayAdapter<CharSequence>(this, R.layout.common_spinner, sex);
     * nameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     * spinner_sex.setAdapter(nameAdapter); if (pet != null && pet.getSex().equals("1")) {
     * spinner_sex.setSelection(0); } else if (pet != null && pet.getSex().equals("2")) {
     * spinner_sex.setSelection(1); } spinner_sex.setOnItemSelectedListener(new
     * OnItemSelectedListener() {
     * 
     * @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
     * { if (sex[position].equals("公")) { petsex = "1"; } if (sex[position].equals("母")) { petsex =
     * "2"; } }
     * 
     * @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated
     * method stub } }); ArrayAdapter<CharSequence> zhongleiAdapter = new
     * ArrayAdapter<CharSequence>(this, R.layout.common_spinner, zhonglei);
     * zhongleiAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     * spinner_zhonglei.setAdapter(zhongleiAdapter); if (pet != null &&
     * pet.getPettype().equals("1")) { spinner_zhonglei.setSelection(0); } else if (pet != null &&
     * pet.getPettype().equals("2")) { spinner_zhonglei.setSelection(1); } else if (pet != null &&
     * pet.getPettype().equals("3")) { spinner_zhonglei.setSelection(2); } else if (pet != null &&
     * pet.getPettype().equals("4")) { spinner_zhonglei.setSelection(3); }
     * spinner_zhonglei.setOnItemSelectedListener(new OnItemSelectedListener() {
     * 
     * @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
     * { infos.clear(); if (zhonglei[position].equals("汪星人")) { loadZhongLeiData("1"); petzhonglei =
     * "1"; } if (zhonglei[position].equals("喵星人")) { loadZhongLeiData("2"); petzhonglei = "2"; } if
     * (zhonglei[position].equals("小宠星人")) { loadZhongLeiData("3"); petzhonglei = "3"; } if
     * (zhonglei[position].equals("水星人")) { loadZhongLeiData("4"); petzhonglei = "4"; } }
     * 
     * @Override public void onNothingSelected(AdapterView<?> parent) {
     * 
     * } });
     * 
     * }
     */

    ArrayAdapter<CharSequence> pinZhongAdapter;

    private List<AddPetInfo> infos = new ArrayList<AddPetInfo>();
    private String[] pinzhong = null;

    private void loadZhongLeiData(String type) {
        // 默认
        // pet_pinzhong.setText("金毛");
        // petpinzhong = "金毛";

        RequestParams params = new RequestParams();
        params.put("type", type);
        AddClient.get(Address.PETPINZHONG, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    AddPet addpet = JSON.parseObject(content, AddPet.class);
                    infos = addpet.getArray();
                    pinzhong = new String[infos.size()];
                    for (int i = 0; i < infos.size(); i++) {
                        pinzhong[i] = new String(infos.get(i).getBreed());
                    }
                    // 品种的滚轮
                    new CalendarManager().getPinzhong(getApplicationContext(), pinzhong,
                            findViewById(R.id.addpet), new IRequest<String>() {
                                @Override
                                public void request(String t) {
                                    pet_pinzhong.setText(t);
                                    petpinzhong = pet_pinzhong.getText().toString().trim();

                                    for (int i = 0; i < infos.size(); i++) {
                                        if (infos.get(i).getBreed().equals(petpinzhong)) {
                                            breedid = infos.get(i).breedid;
                                            break;
                                        }
                                    }

                                }
                            });

                    if (getCurrentFocus() != null) {
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                                .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                        InputMethodManager.HIDE_NOT_ALWAYS);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Toast.makeText(getApplicationContext(),
                        getResources().getString(R.string.net_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initClick() {
        if (petid.equals("")) {
            tittle_addpet_content.setText("添加宠物");
            img_tittle.setText("头像");
        } else {
            tittle_addpet_content.setText("编辑宠物信息");
            img_tittle.setText("编辑宠物头像");
        }
        if (pet != null) {
            if (!TextUtils.isEmpty(pet.birth)) {
                pet_birthrday.setText(pet.birth);
            } else {
                pet_birthrday.setText("暂无数据");
            }
        }
        tittle_addpet_cancel.setOnClickListener(this);
        tittle_addpet_ok.setOnClickListener(this);
        petinfo_touxiang.setOnClickListener(this);
        title_left.setOnClickListener(this);
        title_right.setOnClickListener(this);

        rl_pet_birthrday.setOnClickListener(this);
        rl_pet_sex.setOnClickListener(this);
        rl_pet_zhonglei.setOnClickListener(this);
        rl_pet_pinzhong.setOnClickListener(this);

        pet_name.setText(petname);

    }

    private LinearLayout pic_selector_camera;
    private LinearLayout pic_selector_album;
    // 图片文件夹的地址
    private File filepath;
    // 图片的地址
    private File picPath, picPath_camera, picPath_album;
    private AlertDialog dialog;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_addpet_cancel:
                finish();
                break;
            case R.id.tittle_addpet_ok:// 确认添加宠物
                if (CommonUtil.isFastDoubleClick2())
                    return;
                File file = new File(filepath, "upload.jpg");
                String petname = pet_name.getText().toString().trim();
                if (checkPet(petname)) {
                    if (!TextUtils.isEmpty(petpinzhong) && !TextUtils.isEmpty(breedid)) {
                        petAdd(petname, petsex, petzhongleinum, petpinzhong, breedid, file);

                    } else {
                        Toast.makeText(getApplicationContext(), "请完善宠物资料!", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
                break;
            case R.id.petinfo_touxiang:
                showDialog();
                break;
            case R.id.pic_selector_camera:
                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                initFilePath();
                camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picPath));
                startActivityForResult(camera, CAMERA);
                break;
            case R.id.pic_selector_album:

                Intent intent = new Intent("android.intent.action.PICK");
                intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
                initFilePath();
                // filepath = new File(Environment.getExternalStorageDirectory(), "temp");
                // if (!filepath.exists()) {
                // filepath.mkdirs();
                // }
                // picPath_album =
                // new File(filepath, "albumpet" + System.currentTimeMillis() + ".jpg");
                intent.putExtra("output", Uri.fromFile(picPath));
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 1);// 裁剪框比例
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", crop);// 输出图片大小
                intent.putExtra("outputY", crop);
                startActivityForResult(intent, ALBUM);



                // Intent album = new Intent("android.intent.action.PICK");
                // album.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
                // initFilePath();
                // album.putExtra("output", Uri.fromFile(picPath));
                // // // 不让裁剪
                // // album.putExtra("crop", "true");
                // album.putExtra("crop", "false");
                // //
                // album.putExtra("aspectX", 1);// 裁剪框比例
                //
                // album.putExtra("aspectY", 1);
                //
                // album.putExtra("outputX", crop);// 输出图片大小
                //
                // album.putExtra("outputY", crop);
                // album.putExtra("return-data", true);
                // startActivityForResult(album, ALBUM);

                // Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
                // openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                // "image/*");
                // initFilePath();
                // openAlbumIntent.putExtra("output", Uri.fromFile(picPath));
                // startActivityForResult(openAlbumIntent, ALBUM);

                break;
            case R.id.title_left:
                addpet.setVisibility(View.VISIBLE);
                picinfo.setVisibility(View.GONE);
                break;
            case R.id.title_right:
                handler.sendEmptyMessage(0);
                break;
            case R.id.rl_pet_birthrday:// 选择宠物生日
                if (!CommonUtil.isFastDoubleClick()) {
                    new CalendarManager().getCalendar(getApplicationContext(),
                            findViewById(R.id.addpet), new IRequest<String>() {
                                @Override
                                public void request(String t) {
                                    pet_birthrday.setText(t);
                                    birth = pet_birthrday.getText().toString().trim();
                                }
                            });
                    if (getCurrentFocus() != null) {
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                                .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                        InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                break;
            case R.id.rl_pet_sex:// 选择宠物性别
                if (CommonUtil.isFastDoubleClick())
                    break;
                // pet_sex.setText("公");
                // petsex = "1";
                new CalendarManager().getsex(getApplicationContext(), findViewById(R.id.addpet),
                        new IRequest<String>() {
                            @Override
                            public void request(String t) {
                                pet_sex.setText(t);
                                String petsex1 = pet_sex.getText().toString().trim();
                                if (petsex1.equals("公")) {
                                    petsex = "1";
                                }
                                if (petsex1.equals("母")) {
                                    petsex = "2";
                                }
                            }
                        });

                if (getCurrentFocus() != null) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                }
                break;
            case R.id.rl_pet_zhonglei:// 选择宠物类别
                if (CommonUtil.isFastDoubleClick())// 防止快速点击
                    break;
                // 随意给定一个默认值
                // pet_zhonglei.setText("汪星人");
                // petzhongleinum = "1";
                new CalendarManager().getZhonglei(getApplicationContext(),
                        findViewById(R.id.addpet), new IRequest<String>() {
                            @Override
                            public void request(String t) {
                                pet_zhonglei.setText(t);
                                petzhonglei = pet_zhonglei.getText().toString().trim();

                                if (petzhonglei.equals("汪星人")) {
                                    // loadZhongLeiData("1");
                                    petzhongleinum = "1";
                                }
                                if (petzhonglei.equals("喵星人")) {
                                    // loadZhongLeiData("2");
                                    petzhongleinum = "2";
                                }
                                if (petzhonglei.equals("小宠星人")) {
                                    // loadZhongLeiData("3");
                                    petzhongleinum = "3";
                                }
                                if (petzhonglei.equals("水星人")) {
                                    // loadZhongLeiData("4");
                                    petzhongleinum = "4";
                                }

                            }
                        });

                if (getCurrentFocus() != null) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                }
                break;
            case R.id.rl_pet_pinzhong:// 选择宠物品种
                if (CommonUtil.isFastDoubleClick())// 防止快速点击
                    break;
                String petzhonglei = pet_zhonglei.getText().toString().trim();
                if (!petzhonglei.isEmpty() && !"".equals(petzhongleinum)) {
                    // if (petzhonglei.equals("汪星人")) {
                    // loadZhongLeiData("1");
                    // petzhonglei = "1";
                    // }
                    // if (petzhonglei.equals("喵星人")) {
                    // loadZhongLeiData("2");
                    // petzhonglei = "2";
                    // }
                    // if (petzhonglei.equals("小宠星人")) {
                    // loadZhongLeiData("3");
                    // petzhonglei = "3";
                    // }
                    // if (petzhonglei.equals("水星人")) {
                    // loadZhongLeiData("4");
                    // petzhonglei = "4";
                    // }
                    loadZhongLeiData(petzhongleinum);


                } else {
                    Toast.makeText(getApplicationContext(), "请选择种类", 0).show();
                }
                break;
            default:
                break;
        }
    }

    private String birth = "";

    private void petAdd(final String petname2, final String petsex2, final String petzhonglei2,
            final String petpinzhong2, final String breedid, final File file) {
        final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        if (!petid.equals("")) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        String result =
                                changePet(petname2, petsex2, petzhonglei2, petpinzhong2, breedid,
                                        file);
                        UploadInfo parseObject = JSON.parseObject(result, UploadInfo.class);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ProgressDialog.cancel();
                            }
                        });
                        if (parseObject.getResult().equals("0")) {
                            handler.sendEmptyMessage(SUCCESS);
                        } else {
                            handler.sendEmptyMessage(FAIL);
                        }
                    } catch (Exception e) {
                    }
                }
            }).start();
        } else {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ProgressDialog.cancel();
                        }
                    });
                    try {
                        String result =
                                addPet(petname2, petsex2, petzhonglei2, petpinzhong2, breedid, file);
                        final UploadInfo parseObject = JSON.parseObject(result, UploadInfo.class);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ProgressDialog.cancel();
                                if (parseObject != null
                                        && !TextUtils.isEmpty(parseObject.jifentishi))
                                    CommonUtil.showDialog2(AddPetActivity.this,
                                            parseObject.jifentishi);
                            }
                        });
                        if (parseObject.getResult().equals("0")) {
                            handler.sendEmptyMessage(SUCCESS);
                        } else {
                            handler.sendEmptyMessage(FAIL);
                        }
                    } catch (Exception e) {
                    }
                }
            }).start();
        }

    }

    private String changePet(String petname2, String petsex2, String petzhonglei2,
            String petpinzhong2, String breedid, File file) {
        try {
            MultipartEntity params = new MultipartEntity(); // 文件传输
            params.addPart("petid", new StringBody(petid, Charset.forName("GBK")));
            params.addPart("uid", new StringBody(UserState.getUserUid(), Charset.forName("GBK")));
            params.addPart("username",
                    new StringBody(UserState.getUser().username, Charset.forName("GBK")));
            params.addPart("title", new StringBody(petname2, Charset.forName("GBK")));
            params.addPart("sex", new StringBody(petsex2, Charset.forName("GBK")));
            params.addPart("pettype", new StringBody(petzhonglei2, Charset.forName("GBK")));
            params.addPart("breed", new StringBody(petpinzhong2, Charset.forName("GBK")));
            params.addPart("birth", new StringBody(birth, Charset.forName("GBK")));
            params.addPart("breedid", new StringBody(breedid, Charset.forName("GBK")));
            if (file.exists()) {
                params.addPart("file", new FileBody(file));
            }
            return post(Address.CHANGEPET, params);
        } catch (Exception e) {
        }
        return null;
        // final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        // utils.send(HttpMethod.POST, Address.CHANGEPET, params, new RequestCallBack<String>() {
        // @Override
        // public void onSuccess(ResponseInfo<String> responseInfo) {
        // if (null != ProgressDialog && ProgressDialog.isShowing()) {
        // ProgressDialog.dismiss();
        // }
        // try {
        // UploadInfo parseObject =
        // JSON.parseObject(responseInfo.result, UploadInfo.class);
        // if (parseObject.getResult().equals("0")) {
        // handler.sendEmptyMessage(SUCCESS);
        // } else {
        // handler.sendEmptyMessage(FAIL);
        // }
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        //
        // }
        //
        // @Override
        // public void onFailure(HttpException error, String msg) {
        // if (null != ProgressDialog && ProgressDialog.isShowing()) {
        // ProgressDialog.dismiss();
        // }
        // }
        // });
    }

    private String addPet(String petname2, String petsex2, String petzhonglei2,
            String petpinzhong2, String breedid, File file) {
        try {
            MultipartEntity params = new MultipartEntity(); // 文件传输
            params.addPart("uid", new StringBody(UserState.getUserUid(), Charset.forName("GBK")));
            params.addPart("username",
                    new StringBody(UserState.getUser().username, Charset.forName("GBK")));
            params.addPart("title", new StringBody(petname2, Charset.forName("GBK")));
            params.addPart("sex", new StringBody(petsex2, Charset.forName("GBK")));
            params.addPart("pettype", new StringBody(petzhonglei2, Charset.forName("GBK")));
            params.addPart("breed", new StringBody(petpinzhong2, Charset.forName("GBK")));
            params.addPart("birth", new StringBody(birth, Charset.forName("GBK")));
            params.addPart("breedid", new StringBody(breedid, Charset.forName("GBK")));
            if (file.exists()) {
                params.addPart("file", new FileBody(file));
            }

            return post(Address.PETADD, params);
        } catch (Exception e) {
        }

        return null;
        // final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        // utils.send(HttpMethod.POST, Address.PETADD, params, new RequestCallBack<String>() {
        // @Override
        // public void onSuccess(ResponseInfo<String> responseInfo) {
        // if (null != ProgressDialog && ProgressDialog.isShowing()) {
        // ProgressDialog.dismiss();
        // }
        // try {
        // UploadInfo parseObject =
        // JSON.parseObject(responseInfo.result, UploadInfo.class);
        // // JSONObject result = new JSONObject(new String(responseInfo.result));
        // // String score = result.getString("jifentishi");
        // // showEnterDialog("积分+" + score);
        // CommonUtil.showDialog2(AddPetActivity.this, parseObject.jifentishi);
        // if (parseObject.getResult().equals("0")) {
        // handler.sendEmptyMessage(ADDTRUE);
        // } else {
        // handler.sendEmptyMessage(ADDFAIL);
        // }
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // }
        //
        // @Override
        // public void onFailure(HttpException error, String msg) {
        // if (null != ProgressDialog && ProgressDialog.isShowing()) {
        // ProgressDialog.dismiss();
        // }
        // }
        // });
    }

    private String post(String url, MultipartEntity mpEntity) {
        DefaultHttpClient httpclient = (DefaultHttpClient) XDHttpClient.client.getHttpClient();
        if (ConstantsValue.cookieStore != null) {
            httpclient.setCookieStore(ConstantsValue.cookieStore);
        }
        // 设置通信协议版本
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost(url);
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
        // 读取超时
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
        httppost.setEntity(mpEntity);
        String result = "网络连接超时，请稍后再试";
        try {
            final byte[] responseBody = getResponseData(httpclient.execute(httppost).getEntity());
            result = new String(responseBody, "gbk").toString();
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httppost != null) {
                httppost.abort();
            }
        }
        return result;
    }

    protected final int BUFFER_SIZE = 4096;

    private byte[] getResponseData(HttpEntity entity) throws IOException {
        byte[] responseBody = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            if (instream != null) {
                long contentLength = entity.getContentLength();
                if (contentLength > Integer.MAX_VALUE) {
                    throw new IllegalArgumentException(
                            "HTTP entity too large to be buffered in memory");
                }
                int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
                try {
                    ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
                    try {
                        byte[] tmp = new byte[BUFFER_SIZE];
                        int l, count = 0;
                        // do not send messages if request has been cancelled
                        while ((l = instream.read(tmp)) != -1
                                && !Thread.currentThread().isInterrupted()) {
                            count += l;
                            buffer.append(tmp, 0, l);
                            // sendProgressMessage(count, (int) contentLength);
                        }
                    } finally {
                        instream.close();
                    }
                    responseBody = buffer.toByteArray();
                } catch (OutOfMemoryError e) {
                    System.gc();
                    throw new IOException("File too large to fit into available memory");
                }
            }
        }
        return responseBody;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);



        if (resultCode != RESULT_OK) {
            return;
        }


        if (requestCode == CAMERA) {
            // if (ConstantsValue.uri2 == null) {
            // Toast.makeText(this, "没有选取图片444", 0).show();
            // return;
            // }
            // if (data == null) {
            // Toast.makeText(this, "没有选取图片444", 0).show();
            // return;
            // }
            // addpet.setVisibility(View.GONE);
            // picinfo.setVisibility(View.VISIBLE);
            startPhotoZoom(Uri.fromFile(picPath));
        }
        // 读取相册缩放图片
        if (requestCode == ALBUM) {

            // Uri uri = data.getData();
            // addpet.setVisibility(View.GONE);
            // picinfo.setVisibility(View.VISIBLE);
            // startPhotoZoom(uri);

            // if (picPath != null && picPath.getAbsolutePath().equals("")) {
            // Toast.makeText(this, "没有选取图片111", 0).show();
            // return;
            // }
            // addpet.setVisibility(View.GONE);
            // picinfo.setVisibility(View.VISIBLE);
            // startPhotoZoom(Uri.fromFile(picPath));


            if (data == null) {
                Toast.makeText(this, "没有选取图片222", 0).show();
                return;
            }

            Bitmap bmp = BitmapFactory.decodeFile(picPath.getAbsolutePath());
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 75, stream);// (0 - 100)压缩文件
            pic_edit.setImageBitmap(bmp);
            pet_img.setImageBitmap(bmp);

            FileOutputStream out;
            try {
                out = new FileOutputStream(new File(filepath, "upload.jpg"));
                bmp.compress(Bitmap.CompressFormat.JPEG, 75, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        if (requestCode == PHOTORESOULT && resultCode == RESULT_OK) {
            if (data == null) {
                Toast.makeText(this, "没有选取图片", 0).show();
                return;
            }
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                if (null != photo) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.PNG, 75, stream);// (0 - 100)压缩文件
                    pic_edit.setImageBitmap(photo);
                    pet_img.setImageBitmap(photo);

                    try {
                        FileOutputStream out =
                                new FileOutputStream(new File(filepath, "upload.jpg"));
                        photo.compress(Bitmap.CompressFormat.JPEG, 75, out);
                        out.flush();
                        out.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

    private void initFilePath() {
        filepath = new File(Environment.getExternalStorageDirectory(), "temp");
        if (!filepath.exists()) {
            filepath.mkdirs();
        }
        picPath = new File(filepath, "pet" + System.currentTimeMillis() + ".jpg");
        ConstantsValue.uri2 = Uri.fromFile(picPath);
    }

    private void showDialog() {
        AlertDialog.Builder builder = new Builder(this);
        View view = View.inflate(AddPetActivity.this, R.layout.pic_selector, null);
        pic_selector_camera = (LinearLayout) view.findViewById(R.id.pic_selector_camera);
        pic_selector_album = (LinearLayout) view.findViewById(R.id.pic_selector_album);

        pic_selector_camera.setOnClickListener(AddPetActivity.this);
        pic_selector_album.setOnClickListener(AddPetActivity.this);

        dialog = builder.create();
        dialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }



    private boolean checkPet(String petname) {
        if (TextUtils.isEmpty(petname)) {
            Toast.makeText(this, "宠物昵称不能为空", 0).show();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", crop);
        intent.putExtra("outputY", crop);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

    public void startPhotoZoom1(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        startActivityForResult(intent, PHOTORESOULT);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // private void showDialog2(String str) {
    // LayoutInflater inflater = getLayoutInflater();
    // View layout = inflater.inflate(R.layout.dialog_one, null);
    // TextView title = (TextView) layout.findViewById(R.id.add_score);
    // title.setText(str);
    // Toast toast = new Toast(getApplicationContext());
    // toast.setGravity(Gravity.CENTER, 0, 0);
    // toast.setDuration(Toast.LENGTH_SHORT);
    // toast.setView(layout);
    // toast.show();
    // }
}
